package juc.lock;

import java.util.concurrent.*;

public class CyclicBarrierTest2 {

    private static ConcurrentHashMap<String,Integer> map=new ConcurrentHashMap<>();

    private static ExecutorService executorService= Executors.newFixedThreadPool(3);

    private static CyclicBarrier cb=new CyclicBarrier(3,()->{
        int result=0;
        for (String s : map.keySet()) {
            result+=map.get(s);
        }
        System.out.println("三人平均成绩为："+result/3+"分");
    });

    public static void count(){
        for (int i=0;i<3;i++){
            executorService.execute(()->{
                //获取学生的平均成绩
                int score= (int) (Math.random()*40+60);
                map.put(Thread.currentThread().getName(),score);
                System.out.println(Thread.currentThread().getName()+"同学的平均成绩为："+score);
                try {
                    //执行完允许await();等待所有学生平均成绩计算完毕
                    cb.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    public static void main(String[] args) {
        count();
    }

}
